<template>
  <div class="layout-container"  style=" max-width:100%;">
    <div class="layout-container-form flex space-between">
      <div class="layout-container-form-handle">
        <el-button type="primary" :icon="Plus" @click="handleAdd">{{
          $t("message.common.add")
        }}
        </el-button>
        <el-popconfirm title="确定删除选中的数据吗？" @confirm="handleDel(chooseData)">
          <template #reference>
            <el-button type="danger" :icon="Delete" :disabled="chooseData.length === 0">批量删除 </el-button>
          </template>

        </el-popconfirm>

        <el-button v-show="!editingAll" type="primary" @click="handleEditAll">
          {{ $t("message.common.editBat") }}
        </el-button>

        <el-button v-show="editingAll" type="success" @click="handleSaveAll">
          {{ $t("message.common.saveBat") }}
        </el-button>

        <el-button v-show="editingAll" type="danger" @click="handleCancelEditAll">
          {{ $t("message.common.cancelBat") }}
        </el-button>

      </div>
      <div class="layout-container-form-search">
        <el-input v-model="query.input" :placeholder="$t('message.common.searchTip')"
          @change="handleInputChange(query.input)"></el-input>
        <el-button type="primary" :icon="Search" class="search-btn" @click="handleInputChange(query.input)">{{
          $t("message.common.search") }}
        </el-button>
      </div>
    </div>
    <div class="layout-container-table">
      <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true" :data="tableData"
        @getTableData="getTableData" @selection-change="handleSelectionChange">
        <el-table-column fixed label="Id" align="center" width="80px">
          <template v-slot="{ row, $index }">
            {{ calculateId($index) }}
          </template>
        </el-table-column>

        <el-table-column fixed prop="id" align="center" label="教师号" width="140px">
          <template #default="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column fixed prop="name" align="center" label="姓名">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.name }}</span>
            <el-input v-else-if="editingAll" @change="addToBuffer(row)" v-model="row.name"></el-input>

          </template>
        </el-table-column>

        <el-table-column fixed prop="gender" align="center" label="性别" width="80px">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.gender }}</span>
            <el-select v-else-if="editingAll" @change="addToBuffer(row)" v-model="row.gender" placeholder="请选择"
              clearable>
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column fixed prop="school" align="center" label="学校">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.school }}</span>
            <el-select v-else-if="editingAll" v-model="row.school" filterable placeholder="选择学校"
              @focus="handleGetAllSchool(row)" @change="handleChangeSchool(row)" style="width: 240px">
              <el-option v-for="(school, index) in schoolList" :key="index" :label="school" :value="school" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column fixed prop="college" align="center" label="学院">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.college }}</span>
            <el-select v-else-if="editingAll" v-model="row.college" filterable placeholder="选择学院"
              @focus="handleGetCollege(row)" @change="handleChangeCollege(row)" :disabled="!isSchoolSelected(row)"
              style="width: 240px">
              <el-option v-for="(college, index) in collegeList" :key="index" :label="college" :value="college" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column fixed prop="phone" align="center" label="手机号" width="140px">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.phone }}</span>
            <el-input v-else-if="editingAll" v-model="row.phone" @change="addToBuffer(row)"></el-input>
          </template>
        </el-table-column>

        <el-table-column fixed prop="email" align="center" label="邮箱">
          <template #default="{ row }">
            <span v-if="!(editingAll)">{{ row.email }}</span>
            <el-input v-else-if="editingAll" v-model="row.email" @change="addToBuffer(row)"></el-input>
          </template>
        </el-table-column>

        <el-table-column :label="$t('message.common.handle')" align="center" fixed="right">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)">{{
          $t("message.common.update")
        }}
            </el-button>
            <el-popconfirm :title="$t('message.common.delTip')" @confirm="handleDel([scope.row])">
              <template #reference>
                <el-button type="danger">{{ $t("message.common.del") }}</el-button>
              </template>
            </el-popconfirm>


          </template>
        </el-table-column>
      </Table>
      <Layer :layer="layer" @getTableData="getTableData" v-if="layer.show" />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watchEffect } from "vue";
import { Page } from "@/components/table/type";
import {
  deleteTeacherAccountsApi,
  getTeacherAccountsApi,
  updateTeacherAccountsApi
} from "@/api/accountManagement";
import { LayerInterface } from "@/components/layer/index.vue";
import { ElMessage } from "element-plus";
import Table from "@/components/table/index.vue";
import Layer from "./layer.vue";
import { Plus, Delete, Search } from '@element-plus/icons'
import FilterSelector from "@/views/main/admin/accountManagement/teacherAccount/filterSelector.vue";
import { onBeforeRouteLeave } from 'vue-router';
import { getAllSchoolApi, getCollegeBySchoolApi } from "@/api/user"

export default defineComponent({

  methods: {
  },
  components: {
    FilterSelector,
    Table,
    Layer,
  },
  setup() {
    // 存储搜索用的数据
    const schoolList = ref([])
    const collegeList = ref([])

    // 存储搜索用的数据
    const query = reactive({
      input: "",
    });

    // 弹窗控制器
    const layer: LayerInterface = reactive({
      show: false,
      title: "新增",
      showButton: true,
    });
    // 分页参数, 供table使用
    const page: Page = reactive({
      index: 1,
      size: 20,
      total: 0,
    });
    const filter_methods = reactive({
      selector: null,
      input_str: '',
    })
    const loading = ref(true);
    const tableData = ref([]); // 表格数据
    const buffer = ref([]) // 数据缓冲区，保存待修改的数据
    const chooseData = ref([]);
    const editingRow = ref([]);    // 当前编辑的行
    const editingAll = ref(false);
    const curRow = ref([]);
    // 使用 computed 计算其他两个选择框的可选状态
    const isSchoolSelected = (row: any) => {
      return row.school !== '';
    };

    const isCollegeSelected = (row: any) => {
      return row.school !== '' && row.college !== '';
    };
    const handleChangeSchool = (row: any) => {
      addToBuffer(row);
      row.college = '';
    };
    const handleChangeCollege = (row: any) => {
      addToBuffer(row);
    };
    watchEffect((row: any) => {
      if (row.school === '') {
        row.college = '';
      }
    });
    const handleGetAllSchool = (row: any) => {
      getAllSchoolApi().then(response => {
        schoolList.value = response.data;
      })
    }
    const handleGetCollege = (row: any) => {
      getCollegeBySchoolApi(row).then(response => {
        collegeList.value = response.data;
      })
    }

    onBeforeRouteLeave((to, from, next) => {
      handleCancelEditAll();
      next();
    });
    const handleSelectionChange = (val: []) => {
      
      chooseData.value = val;
      console.log("选中 val = ", val)
      console.log("选中 chooseData = ", chooseData.value)
    };
    // 获取表格数据
    // params <init> Boolean ，默认为false，用于判断是否需要初始化分页
    function isEditing(row: []) {
      return editingRow.value === row;
    }

    const handleInputChange = (input_str: string) => {
      filter_methods.input_str = input_str;
      getTableData(true)
    }



    function handleEditAll() {
      editingAll.value = !editingAll.value;
      editingRow.value = null; // 清空单独编辑的行
      tableData.value.forEach((row) => {
        if (row.dirty) {
          addToBuffer(row);
        }
      })
    }

    function addToBuffer(row: any) {
      const index = buffer.value.findIndex((item: any) => item.id === row.id);

      if (index !== -1) {
        // 根据学号匹配缓冲区中的数据，如果有相同学号则覆盖，否则加入缓冲区
        buffer.value[index] = row;
      } else {
        // 加入缓冲区
        buffer.value.push(row);
      }
    }

    function handleSaveAll() {
      // 处理保存逻辑
      console.log('更新前：', buffer.value)
      updateTeacherAccountsApi(buffer.value).then((response: any) => {
        // 处理成功的情况
        if (response.code === 200) {
          ElMessage.success('更新成功')
        } else {
          ElMessage.error('更新失败')
        }
      }).catch(error => {
        // 处理失败的情况
        ElMessage.error(error)
      }).finally(() => {
        // 清空缓冲区和关闭编辑状态
        buffer.value = [];
        editingAll.value = false;
      });
    }

    function handleCancelEditAll() {
      // 处理保存逻辑
      buffer.value = [];
      editingAll.value = false;
      getTableData(true);
    }

    const getTableData = (init: Boolean) => {
      loading.value = true
      if (init) {
        page.index = 1
      }
      let params = {
        page: page.index,
        pageSize: page.size,
        filter_methods: filter_methods,
        ...query
      }
      


      getTeacherAccountsApi(params)
        .then((res) => {
          let data = res.data.data;
          data.forEach((d: any) => {
            d.loading = false;
          });
          tableData.value = data;
          page.total = res.data.total_size;
        })
        .catch((error) => {
          console.error('发生错误:', error);
          tableData.value = [];
          page.index = 1;
          page.total = 0;
        })
        .finally(() => {
          loading.value = false;
        });
    }


    // 删除功能
    const handleDel = (data: object[]) => {
      deleteTeacherAccountsApi(data).then((response: any) => {
        // 处理成功的情况
        if (response.code === 200) {
          ElMessage.success('删除成功')
        } else {
          ElMessage.error('删除失败')
        }
      }).catch(error => {
        // 处理失败的情况
        ElMessage.error(error)
      }).finally(() => {
        // // 清空缓冲区和关闭编辑状态
        getTableData(true)
      });
    }
    const calculateId = (index: number) => {
      // 根据 page、pagesize 和当前行的索引计算出 "Id" 列的值
      return (page.index - 1) * page.size + index + 1;
    };
    // 新增弹窗功能
    const handleAdd = () => {
      layer.title = "新增数据";
      layer.show = true;
      delete layer.row;
    }
    // 编辑弹窗功能
    const handleEdit = (row: any) => {
      layer.title = "编辑数据";
      layer.row = row;
      layer.show = true;
    }

    getTableData(true)
    return {
      Plus,
      Delete,
      Search,
      query,
      tableData,
      buffer,
      chooseData,
      loading,
      page,
      layer,
      editingRow, // 当前编辑的行
      editingAll,
      isEditing,
      handleSelectionChange,
      getTableData,
      handleDel,
      handleAdd,
      handleEdit,
      calculateId,
      handleEditAll,
      addToBuffer,
      handleSaveAll,
      handleCancelEditAll,
      handleInputChange,
      // 修改学校专业
      schoolList,
      collegeList,
      isSchoolSelected,
      isCollegeSelected,
      handleGetCollege,
      handleGetAllSchool,
      handleChangeSchool,
      handleChangeCollege,
    };
  }
});
</script>

<style lang="scss" scoped>
.statusName {
  margin-right: 10px;
}
</style>
